<template>
    <el-container class="repository-container">
        <el-main>
            <!-- 知识库信息头部 -->
            <div class="repository-header">
                <div class="repository-info">
                    <h2>{{ repository.name }}</h2>
                    <p class="description">{{ repository.description }}</p>
                </div>
                <div class="actions">
                    <el-button type="primary" @click="createNote">新建随记</el-button>
                </div>
            </div>

            <!-- 随记列表 -->
            <div class="notes-container">
                <el-empty v-if="notes.length === 0" description="暂无随记" />
                <el-row :gutter="20" v-else>
                    <el-col v-for="note in notes" :key="note.id" :xs="24" :sm="12" :md="8" :lg="6">
                        <el-card class="note-card" shadow="hover">
                            <template #header>
                                <div class="card-header">
                                    <span class="title">{{ note.title }}</span>
                                    <div class="actions">
                                        <el-dropdown trigger="click" @command="handleCommand($event, note.id)">
                                            <el-button type="primary" text>
                                                <el-icon>
                                                    <More />
                                                </el-icon>
                                            </el-button>
                                            <template #dropdown>
                                                <el-dropdown-menu>
                                                    <el-dropdown-item command="edit">编辑</el-dropdown-item>
                                                    <el-dropdown-item command="remove" divided>移出知识库</el-dropdown-item>
                                                    <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                                                </el-dropdown-menu>
                                            </template>
                                        </el-dropdown>
                                    </div>
                                </div>
                            </template>
                            <div class="card-content" @click="openNote(note.id)">
                                <p class="preview">{{ getContentPreview(note.content) }}</p>
                                <div class="meta">
                                    <span class="time">{{ formatDate(note.updateTime) }}</span>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
        </el-main>
    </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { More } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const baseURL = 'http://127.0.0.1:3000'
const route = useRoute()
const router = useRouter()
const repository = ref({})
const notes = ref([])

// 获取知识库详情
const fetchRepository = async () => {
    try {
        const response = await fetch(`${baseURL}/api/repositories/${route.params.id}`, {
            headers: {
                Authorization: 'Bearer ' + userStore.token,
            },
        })
        if (!response.ok) throw new Error('获取知识库详情失败')
        repository.value = await response.json()
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 获取知识库下的随记
const fetchNotes = async () => {
    try {
        const response = await fetch(`${baseURL}/api/notes?repositoryId=${route.params.id}`,
            {
                headers: {
                    Authorization: 'Bearer ' + userStore.token,
                },
            }
        )
        if (!response.ok) throw new Error('获取随记列表失败')
        notes.value = await response.json()
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 新建随记
const createNote = async () => {
    router.push({
        path: '/file/new',
        query: { repositoryId: route.params.id }
    })
}

// 处理随记操作
const handleCommand = async (command, noteId) => {
    switch (command) {
        case 'edit':
            router.push(`/file/${noteId}`)
            break
        case 'remove':
            await removeNoteFromRepo(noteId)
            break
        case 'delete':
            await deleteNote(noteId)
            break
    }
}

// 移出知识库
const removeNoteFromRepo = async (noteId) => {
    try {
        await ElMessageBox.confirm('确定要将此随记从知识库中移出吗？', '提示', {
            type: 'warning'
        })

        const response = await fetch(`${baseURL}/api/notes/${noteId}/repository`, {
            method: 'DELETE',
            headers: {
                Authorization: 'Bearer ' + userStore.token,
            }
        })

        if (!response.ok) throw new Error('移出知识库失败')

        await fetchNotes()
        ElMessage.success('移出知识库成功')
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(error.message)
        }
    }
}

// 删除随记
const deleteNote = async (noteId) => {
    try {
        await ElMessageBox.confirm('确定要删除此随记吗？此操作不可恢复。', '警告', {
            type: 'warning'
        })

        const response = await fetch(`${baseURL}/api/notes/${noteId}`, {
            method: 'DELETE',
            headers: {
                Authorization: 'Bearer ' + userStore.token,
            }
        })

        if (!response.ok) throw new Error('删除随记失败')

        await fetchNotes()
        ElMessage.success('删除随记成功')
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(error.message)
        }
    }
}

// 打开随记
const openNote = (noteId) => {
    router.push(`/file/${noteId}`)
}

// 获取内容预览
const getContentPreview = (content) => {
    if (!content) return '暂无内容'
    // 移除HTML标签
    const plainText = content.replace(/<[^>]*>/g, '')
    return plainText.length > 100 ? plainText.slice(0, 100) + '...' : plainText
}

// 格式化日期
const formatDate = (date) => {
    if (!date) return ''
    return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    })
}

onMounted(() => {
    fetchRepository()
    fetchNotes()
})
</script>

<style scoped>
.repository-container {
    padding: 20px;
}

.repository-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
}

.repository-info {
    h2 {
        margin: 0;
        font-size: 24px;
        color: #303133;
    }

    .description {
        margin: 8px 0 0;
        color: #909399;
        font-size: 14px;
    }
}

.notes-container {
    margin-top: 20px;
}

.note-card {
    margin-bottom: 20px;
    transition: all 0.3s;

    &:hover {
        transform: translateY(-2px);
    }

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
            font-size: 16px;
            font-weight: 500;
            color: #303133;
        }
    }

    .card-content {
        cursor: pointer;

        .preview {
            margin: 0;
            font-size: 14px;
            color: #606266;
            line-height: 1.6;
            height: 66px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
        }

        .meta {
            margin-top: 12px;
            font-size: 12px;
            color: #909399;
        }
    }
}
</style>
